<?php
class Ecore_Function {
	public static function script($strScript){
		echo '<script language="javascript" type="text/javascript">';
		echo $strScript;
		echo '</script>';
	}
	public static function redirect($strUrl) {
		header('location: ' . $strUrl);
	}
	public static function isCached(&$result = null, $intDataType = 0) {
		if (!$result) return 0;
		if ($result == NOCACHE) {
			$result = null;
		}
		return 1;
	}
	public static function file_get_contents_curl($url)
	{
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_ENCODING, '');  
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
	
	public static function convertDateSys($intDay, $intMonth, $intYear) {
		return $intYear . '-' . $intMonth . '-' . $intDay;
	}	
	public static function getDayInMonth($intYear, $intMonth) {		
		$intMonth 	= intval($intMonth);
		switch($intMonth) {
			case 2:
				$intYear = intval($intMonth);
				if($intYear%4==0)
					return Ecore_Function::arrayNumber(1,29,1);
				else
					return Ecore_Function::arrayNumber(1,28,1);
				break;
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				return Ecore_Function::arrayNumber(1,31,1);
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				return Ecore_Function::arrayNumber(1,30,1);
				break;
			default:
				break;
		}
	}
	public static function arrayNumber($intMin = 0, $intMax = 0, $isEqualLength = 0)
	{
		for ($i = $intMin; $i <= $intMax; $i++) {
			$v = $i;
			if( $isEqualLength == 1 ) $v = substr(str_pad($i, strlen($intMax), '0', STR_PAD_LEFT), strlen($intMax) * -1);
			$arrResult[$v] = intval($v);
		}
		return $arrResult;
	}
	public static function getYear() {
		$intMin 	= intval(date('Y')) - 99;
		$intMax		= intval(date('Y')) - 10;		
		for ($i = $intMax; $i >= $intMin; $i--) {
			$v = $i;
			$arrResult[$v] = $v;
		}
		return $arrResult;		
	}	
	public static function now() {
		return date('Y-m-d H:i:s');
	}
	public static function getIp() {
		return (getenv('HTTP_X_FORWARDED_FOR')) ?  getenv('HTTP_X_FORWARDED_FOR') :  getenv('REMOTE_ADDR');
	}
	public static function logDb($strStore)
	{
		print_r($strStore);
		exit();
		$strFolder = ROOT_DIR . '/data/log/' . date('Y/m/d/');
		Ecore_Function::mkDirectory($strFolder);
		$strFile   = $strFolder . 'db.txt';
		$strContent = @file_get_contents($strFile);
		$strContent = $strContent . Ecore_Function::now() . ' - '  . $strStore . "\n::::\n";
		@file_put_contents($strFile, $strContent);
		return null;
	}
	public static function logFile($strFile,$str)
	{
		$strFolder = ROOT_DIR . '/data/log/';
		Ecore_Function::mkDirectory($strFolder);
		$strFile   = $strFolder . $strFile .'.txt';
		$strContent = @file_get_contents($strFile);
		$strContent = $strContent . Ecore_Function::now() . ' - '  . $str . "\n::::\n";
		@file_put_contents($strFile, $strContent);
	}
	public static function urlPaging($intParams = 0, $strName='page')
	{
		$strUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		if ($intParams == 0) {
			$intChr	= '?';
			$intPos	= strpos($strUrl, '?'.$strName.'=');
		} else {
			$intChr	= '&';
			$intPos	= strpos($strUrl, '&'.$strName.'=');
		}
		if ($intPos != false) {
			$strUrl = substr($strUrl, 0, $intPos);
		}
		return $strUrl . $intChr;
	}
	public static function json($name) {
		$arrResult 	= null;
		$strFile	= CONFIG_FOLDER . $name . '.json';			
		if(file_exists($strFile)) {
			$strFile = @file_get_contents($strFile);			
			try {
				$arrResult = Zend_Json::decode($strFile);	
			}catch(Exception $e){
				$arrResult = null;
			}
		}
		return $arrResult;
	}
	public static function base64E($str)
	{
		return str_replace('/', 'ptk', base64_encode($str));
	}

	public static function base64D($str,$option=0)
	{
		if($option == 0) {
			return base64_decode(str_replace('ptk', '/', $str));
		} else {
			return base64_decode($str);
		}
	}
	public static function hex2Dec($strHex)
	{
	    if ($strHex != '' && $strHex > 0) {
			$intIdDecode = hexdec($strHex)-900000000;
			return $intIdDecode;
		}
		return 0;
	}

	public static function dec2Hex($intDec)
	{
	    $strIdEncode = dechex(900000000 + $intDec);
		return strtoupper($strIdEncode);
	}
	public static function setMsg($strMsg)
	{
		$_SESSION[SESSION_MESSAGE] = Ecore_Function::base64E($strMsg);
	}
	public static function getMsg()
	{		
		$strMsg = '';
		if (isset($_SESSION[SESSION_MESSAGE])) {
			$strMsg = Ecore_Function::base64D($_SESSION[SESSION_MESSAGE]);
			unset($_SESSION[SESSION_MESSAGE]);
		}
		return $strMsg;
	}
	public static function setError($strMsg)
	{
		$_SESSION[SESSION_ERROR] = Ecore_Function::base64E($strMsg);
	}
	public static function getError()
	{
		$strMsg = '';
		if (isset($_SESSION[SESSION_ERROR])) {
			$strMsg = Ecore_Function::base64D($_SESSION[SESSION_ERROR]);
			unset($_SESSION[SESSION_ERROR]);
		}
		return $strMsg;
	}
	public static function hash() {
		return md5(uniqid(rand(),1));
	}
	public static function setSecret($intId=0, $strName='', $isSession=1) {
		$strToken = Ecore_Function::getSecret($intId, $strName);
		if($strToken == '') {
			$strToken = md5(uniqid(rand(),1));				
			if($isSession) {	
				$strSession = $strName . $intId;
				$_SESSION[$strSession] = $strToken;
			} 
		}
		return $strToken;
	}
	public static function getSecret($intId, $strName) {
		$strSession = $strName . $intId;
		return isset($_SESSION[$strSession]) ? $_SESSION[$strSession] : '';
	}
	public static function deleteSecret($intId, $strName) {
		$strSession = $strName . $intId;
		if(isset($_SESSION[$strSession])) {
			unset($_SESSION[$strSession]);
		}
	}
	public static function getCookie($strName)
	{
		return (isset($_COOKIE[$strName]) ? $_COOKIE[$strName] : '');
	}
	public static function setCookie($strName, $value, $expire = 0, $domain = DOMAIN)
	{
		if ($expire == 0) {
			$expire = time() + 14*24*60*60;
		} else {
			$expire = time() + $expire;
		}
		return setcookie($strName, $value, $expire, '/', '.' . $domain);
	}

	public static function deleteCookie($strName, $domain = DOMAIN)
	{
		//setcookie($strName, '', 1, '/', '.' . $domain);
		setcookie($strName, '', time()-3600);
	}
	public static function mkDirectory($target) {
		// from php.net/mkdir user contributed notes
		if (file_exists ( $target )) {
			if (! @ is_dir ( $target ))
				return false;
			else
				return true;
		}
		
		// Attempting to create the directory may clutter up our display.
		if (@ mkdir ( $target )) {
			$stat = @ stat ( dirname ( $target ) );
			$dir_perms = $stat ['mode'] & 0007777; // Get the permission bits.
			@ chmod ( $target, $dir_perms );
			return true;
		} else {
			if (is_dir ( dirname ( $target ) ))
				return false;
		}
		
		// If the above failed, attempt to create the parent node, then try again.
		if (Ecore_Function::mkDirectory ( dirname ( $target ) ))
			return mkDir ( $target );
		
		return false;
	}
	public static function convertArrToStr($arr) {
		
		if(is_array($arr)) {
			$str = '';
			$length = count($arr);			
			for($i=0;$i<$length;$i++) {
				$str .= $arr[$i];
				if($length-$i > 1) {
					$str .=',';
				}
			}
			return $str;
		}
		return '';
	}
	public static function convertArrToInt($arr) {
		if(is_array($arr)) {
			$int = '';
			$length = count($arr);
			for($i=0;$i<$length;$i++) {
				$int += $arr[$i];				
			}
			return $int;
		}
		return -1;
	}	
	public static function isValidDate($str) {
		if($str == '') return false;
		$arrExp 	= explode('/', $str);
		$intDay		= isset($arrExp[0]) ? (int)$arrExp[0] : null;
		$intMonth	= isset($arrExp[1]) ? (int)$arrExp[1] : null;	
		$intYear	= isset($arrExp[2]) ? (int)$arrExp[2] : null;	
		return checkdate($intMonth, $intDay, $intYear);
	}
	public static function isValidHour($intHour, $intMinute) {	
		if((int)$intHour < 24 && (int)$intMinute < 60) {				
			return true;
		}else {
			return false;
		}
	}
	public static function isValidUsername($strUsername) {
		if(preg_match('/^(([A-Za-z\d][A-Za-z\d_]{4,29}[a-zA-Z\d])|([a-zA-Z\d]{5,30}))$/', $strUsername)) {
			return true;
		}
		return false;
	}
	public static function isValidMobile($strMobile) {
		if(preg_match('/^((09[\d]{8})|(^01[\d]{9}))$/', $strMobile)) {
			return true;
		}
		return false;
	}
	public static function isValidObject($strLink) {			
		if(preg_match('/^<object[^>]*?.*?<\/object>$/', $strLink)) {			
			return true;
		}
		return false;
	}
	public static function isValidLink($strLink) {
		if($strLink == '') return false;
		$strWww		= 'www.' . DOMAIN;
		$arrDomain	= array(DOMAIN=>DOMAIN, $strWww=>$strWww);
		$strDomain 	= parse_url($strLink, PHP_URL_HOST);
		$strIp		= gethostbyname($strDomain);
		if(array_key_exists($strDomain, $arrDomain)) {
			return true;
		}
		return false;		
	}
	public static function isValidCode($strCode) {		
		if(preg_match('/^([a-zA-Z_]{2,50})$/', $strCode)) {			
			return true;
		}
		return false;
	}
	public static function validateUrl($str)
	{
		return preg_match("/^(http|https|ftp):\/\/([a-z0-9]([a-z0-9_-]*[a-z0-9])?\.)+[a-z]{2,6}\/?([a-z0-9\?\._-~&#=+%]*)?/", $str);
	}
	public static function getBrowser() {
		$u_agent 	= $_SERVER['HTTP_USER_AGENT'];
		$ub			= '';
		if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)  || preg_match('/Gecko/i',$u_agent))
		{
			$ub = "MSIE";
		}
		elseif(preg_match('/Firefox/i',$u_agent))
		{
			$ub = "Firefox";
		}
		elseif(preg_match('/Chrome/i',$u_agent))
		{
			$ub = "Chrome";
		}
		elseif(preg_match('/Safari/i',$u_agent))
		{
			$ub = "Safari";
		}
		elseif(preg_match('/Opera/i',$u_agent))
		{
			$ub = "Opera";
		}
		elseif(preg_match('/Netscape/i',$u_agent))
		{
			$ub = "Netscape";
		} 
		return $ub;
	}
	public static function convertStrToDate($strDate) {
		if($strDate == '') return '';
		$arrExplode = explode('/', $strDate);		
		if(count($arrExplode) > 1) {
			return $arrExplode[2] . '-' . $arrExplode[1] . '-' . $arrExplode[0];
		}
		return '';
	}
	public static function price($str) {
		return str_replace('.','',$str);
	}
	public static function stripTags($strSrc, $intType=1)
	{
		$strSrc	= urldecode($strSrc);	
		$strSrc = str_replace(array('&lt;','&gt;','\\'), array('<', '>',''), $strSrc);
		$strSrc = str_replace(	array('[B]','[/B]','[I]','[/I]','[U]','[/U]','[b]','[/b]','[i]','[/i]','[u]','[/u]'),
								array('<strong>','</strong>','<em>','</em>','<span style="text-decoration:underline;">','</span>','<strong>','</strong>','<em>','</em>','<span style="text-decoration:underline;">','</span>'),
								$strSrc);
		$strSrc	= html_entity_decode($strSrc, ENT_NOQUOTES, 'UTF-8');
		$strSrc = trim($strSrc);
		if($intType == -3) {			
			$strAllowTags = '<strong>,<em>,<u>,<br/>,<br />,' . "\n";
		} elseif($intType == -2) {
			$strAllowTags	= '';
		} elseif($intType == 0) {
			$strAllowTags	= "\n";
		} elseif($intType == 1) { 
			$strAllowTags 	= '<p>,<font>,<span>,<a>,<img>,<h1>,<h2>,<h3>,<h4>,<h5>,<h6>,<strong>,<b>,<em>,<i>,<br/>,<br />,<u>,' . "\n";
		} elseif($intType == 2) { // cmt
			$strAllowTags 	= '<a>,<img>,<br/>,<br />' . "\n";
		} elseif($intType == 3) { // cmt has quote
			$strAllowTags	= '<p>,<strong>,<b>,<em>,<i>,<u>,<span>,<img>,<br/>,<br />' . "\n";
		} elseif($intType == 4) { // smart search
			$strAllowTags	= '<ul>,<li>,<a>,<strong>';
		} else { // create
			$strAllowTags 	= '<p>,<font>,<span>,<a>,<img>,<h1>,<h2>,<h3>,<h4>,<h5>,<h6>,<strong>,<b>,<em>,<i>,<u>,<br/>,' . "\n" . ',<sub>,<sub>,<video>,<iframe>,<object>,<param>,<embed>,<ul>,<ol>,<li>,<table>,<tbody>,<thead>,<tfoot>,<tr>,<th>,<td>';
		}
		$strSrc = strip_tags($strSrc, $strAllowTags);		
		return trim($strSrc);
	}
	public static function getUrl($strLink='') {
		
		$ref = $_SERVER['REQUEST_URI'];
		$arr = parse_url($ref);
		if($strLink == '')
			$strLink = 'http://' . $_SERVER['SERVER_NAME'];
		elseif(substr($strLink,-1) == '/')
			$strLink = substr($strLink, 0, -1);
		if(isset($arr['query'])) {
			parse_str($arr['query'], $query);	
			if(isset($query['page']))
				unset($query['page']);
			$arr['query'] 	= http_build_query($query);
			if($arr['query'] == '') {
				return $strLink.$arr['path'].'?';
			} else {
				return $strLink.$arr['path'].'?'.$arr['query'] . '&amp;';
			}
		} else '';
	}
	public static function convertNoVn($string, $length = 100, $strSymbol='-', $isToLower = 1)
	{
		$arrCharFrom= array(
							   "ạ","á","à","ả","ã","Ạ","Á","À","Ả","Ã",
							   "â","ậ","ấ","ầ","ẩ","ẫ","Â","Ậ","Ấ","Ầ","Ẩ","Ẫ",
							   "ă","ặ","ắ","ằ","ẳ","ẫ","Ă","Ắ","Ằ","Ẳ","Ẵ","Ặ",
							   "ê","ẹ","é","è","ẻ","ẽ","Ê","Ẹ","É","È","Ẻ","Ẽ",
							   "ế","ề","ể","ễ","ệ","Ế","Ề","Ể","Ễ","Ệ",
							   "ọ","ộ","ổ","ỗ","ố","ồ","Ọ","Ộ","Ổ","Ỗ","Ố","Ồ","Ô","ô",
							   "ó","ò","ỏ","õ","Ó","Ò","Ỏ","Õ",
							   "ơ","ợ","ớ","ờ","ở","ỡ",
							   "Ơ","Ợ","Ớ","Ờ","Ở","Ỡ",
							   "ụ","ư","ứ","ừ","ử","ữ","ự","Ụ","Ư","Ứ","Ừ","Ử","Ữ","Ự",
							   "ú","ù","ủ","ũ","Ú","Ù","Ủ","Ũ",
							   "ị","í","ì","ỉ","ĩ","Ị","Í","Ì","Ỉ","Ĩ",
							   "ỵ","ý","ỳ","ỷ","ỹ","Ỵ","Ý","Ỳ","Ỷ","Ỹ",
							   "đ","Đ"
				   		);
	   $arrCharEndNoVn= array(
							   "a","a","a","a","a","A","A","A","A","A",
							   "a","a","a","a","a","a","A","A","A","A","A","A",
							   "a","a","a","a","a","a","A","A","A","A","A","A",
							   "e","e","e","e","e","e","E","E","E","E","E","E",
							   "e","e","e","e","e","E","E","E","E","E",
							   "o","o","o","o","o","o","O","O","O","O","O","O","O","o",
							   "o","o","o","o","O","O","O","O",
							   "o","o","o","o","o","o",
							   "O","O","O","O","O","O",
							   "u","u","u","u","u","u","u","U","U","U","U","U","U","U",
							   "u","u","u","u","U","U","U","U",
							   "i","i","i","i","i","I","I","I","I","I",
							   "y","y","y","y","y","Y","Y","Y","Y","Y",
							   "d","D"
	   						);
		$arrCharFilter = str_replace($arrCharFrom,$arrCharEndNoVn,trim($string));
		if($strSymbol != '')		{
			if (mb_strlen($arrCharFilter,"UTF-8") > $length) {
				$arrCharFilter = mb_substr($arrCharFilter, 0, $length,"UTF-8");
			}		
			$arrCharFilter = preg_replace('/[\W|_]+/',$strSymbol,$arrCharFilter);
		}
		return $isToLower ? strtolower($arrCharFilter) : $arrCharFilter;
	}
	public static function UTF8Deaccent($str)
	{
		$str	= html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
    	$trans = array
    	(
			// C1 Controls and Latin-1 Supplement (0080 - 00FF)
			'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'È' => 'E',
			'É' => 'E', 'Ê' => 'E', 'Ì' => 'I', 'Í' => 'I',
			'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
			'Ù' => 'U', 'Ú' => 'U', 'à' => 'a', 'á' => 'a',
			'â' => 'a', 'ã' => 'a', 'è' => 'e', 'é' => 'e',
			'ê' => 'e', 'ì' => 'i', 'í' => 'i', 'ò' => 'o',
			'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ù' => 'u',
			'ú' => 'u', 'ý' => 'y',
			// Latin Extended-A (0100 - 017F)
			'Ă' => 'A', 'ă' => 'a', 'Đ' => 'D', 'đ' => 'd',
			'Ĩ' => 'I', 'ĩ' => 'i',	'Ũ' => 'U', 'ũ' => 'u',
			// Latin Extended-B (0180 - 024F)
			'Ơ' => 'O', 'ơ' => 'o',	'Ư' => 'U', 'ư' => 'u',
			// Latin Extended Additional (1E80 - 1EFF)
			'Ạ' => 'A', 'ạ' => 'a',	'Ả' => 'A', 'ả' => 'a',
			'Ấ' => 'A', 'ấ' => 'a',	'Ầ' => 'A', 'ầ' => 'a',
			'Ẩ' => 'A', 'ẩ' => 'a',	'Ẫ' => 'A', 'ẫ' => 'a',
			'Ậ' => 'A', 'ậ' => 'a', 'Ắ' => 'A', 'ắ' => 'a',
			'Ằ' => 'A', 'ằ' => 'a', 'Ẳ' => 'A', 'ẳ' => 'a',
			'Ẵ' => 'A', 'ẵ' => 'a', 'Ặ' => 'A', 'ặ' => 'a',
			'Ẹ' => 'E', 'ẹ' => 'e', 'Ẻ' => 'E', 'ẻ' => 'e',
			'Ẽ' => 'E', 'ẽ' => 'e', 'Ế' => 'E', 'ế' => 'e',
			'Ề' => 'E', 'ề' => 'e', 'Ể' => 'E', 'ể' => 'e',
			'Ễ' => 'E', 'ễ' => 'e', 'Ệ' => 'E', 'ệ' => 'e',
			'Ỉ' => 'I', 'ỉ' => 'i', 'Ị' => 'I', 'ị' => 'i',
			'Ọ' => 'O', 'ọ' => 'o', 'Ỏ' => 'O', 'ỏ' => 'o',
			'Ố' => 'O', 'ố' => 'o', 'Ồ' => 'O', 'ồ' => 'o',
			'Ổ' => 'O', 'ổ' => 'o', 'Ỗ' => 'O', 'ỗ' => 'o',
			'Ộ' => 'O', 'ộ' => 'o', 'Ớ' => 'O', 'ớ' => 'o',
			'Ờ' => 'O', 'ờ' => 'o', 'Ở' => 'O', 'ở' => 'o',
			'Ỡ' => 'O', 'ỡ' => 'o', 'Ợ' => 'O', 'ợ' => 'o',
			'Ụ' => 'U', 'ụ' => 'u', 'Ủ' => 'U', 'ủ' => 'u',
			'Ứ' => 'U', 'ứ' => 'u', 'Ừ' => 'U', 'ừ' => 'u',
			'Ử' => 'U', 'ử' => 'u', 'Ữ' => 'U', 'ữ' => 'u',
			'Ự' => 'U', 'ự' => 'u', 'Ỳ' => 'Y', 'ỳ' => 'y',
			'Ỵ' => 'Y', 'ỵ' => 'y',	'Ỷ' => 'Y', 'ỷ' => 'y',
			'Ỹ' => 'Y', 'ỹ' => 'y'
		);
		return strtr($str, $trans);
	}
	public static function wordCut($sText, $iMaxLength=258, $sMessage='...',$option=0)
	{
		if($option == 0)
			$sText = html_entity_decode(Ecore_Function::stripTags($sText,0), ENT_NOQUOTES, 'UTF-8');	
		elseif($option == 1) 
			$sText = html_entity_decode(Ecore_Function::stripTags($sText,3), ENT_NOQUOTES, 'UTF-8');	
	    if (strlen($sText) > $iMaxLength)
	    {			
			$sString 			= wordwrap($sText, ($iMaxLength-strlen($sMessage)), '[cut]', 1);
			$asExplodedString 	= explode('[cut]', $sString);      
			$sCutText 			= $asExplodedString[0];      
			$sReturn 			= $sCutText . $sMessage;
	    }
	    else
	    {
		   $sReturn = $sText . $sMessage;
	    }	  
		return $sReturn;
	}
	public static function bit($intBit) {
		return (1<<$intBit);
	}
	public static function addZero($str, $length=10) {
		return sprintf('%0' . $length . 's', $str);
	}
	public static function numberFormat($number, $decimals='0', $decpoint=',', $thousandsep='.') {
		return number_format($number, $decimals, $decpoint, $thousandsep);
	}
	public static function formatWithSuffix($number){
		$k 	 = pow(10,3);
		$mil = pow(10,6);
		$bil = pow(10,9);
		if ($number >= $bil) {
			$number = round(($number / $bil),1);
			return str_replace('.0','',$number).'b';
		}
		elseif ($number >= $mil) {
			$number = round(($number / $mil),1);
			return str_replace('.0','',$number).'m';
		}
		elseif ($number >= $k) {
			$number = round(($number / $k),1);
			return str_replace('.0','',$number).'k';
		}
		else
			return (int)$number;
	}
	public static function daysInMonth($month, $year) {
		if(checkdate($month, 31, $year)) return 31;
		if(checkdate($month, 30, $year)) return 30;
		if(checkdate($month, 29, $year)) return 29;
		if(checkdate($month, 28, $year)) return 28;
		return 0; // error
	} 
	
	public static function shuffleAssoc($list,$num=1) { 
		if (!is_array($list)) return $list; 
		$keys = array_keys($list); 
		shuffle($keys); 
		$random = array(); 
		foreach ($keys as $key) { 
			$random[] = $list[$key]; 			
		}
		if($num==1) {			
			return $random[0]; 
		} else {
			return $random; 
		}
	}
	public static function sortByField($multArray, $sortField, $desc=true){
		$tmpKey='';
		$ResArray=array();

		$maIndex=array_keys($multArray);
		$maSize=count($multArray)-1;

		for($i=0; $i < $maSize ; $i++) {

		   $minElement=$i;
		   $tempMin=$multArray[$maIndex[$i]][$sortField];
		   $tmpKey=$maIndex[$i];

			for($j=$i+1; $j <= $maSize; $j++)
			  if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
				 $minElement=$j;
				 $tmpKey=$maIndex[$j];
				 $tempMin=$multArray[$maIndex[$j]][$sortField];

			  }
			  $maIndex[$minElement]=$maIndex[$i];
			  $maIndex[$i]=$tmpKey;
		}

	   if($desc)
		   for($j=0;$j<=$maSize;$j++)
			  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
	   else
		  for($j=$maSize;$j>=0;$j--)
			  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];

	   return $ResArray;
	} 
	public static function getCoordinatesFromAddress( $strAddr, $strCountry='vn', $isLatLng=1)
	{
		$strUrl 	= 'http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($strAddr).'&sensor=false&region='.$strCountry.'&language='.$strCountry;
		$strData 	= file_get_contents($strUrl);
		$arrJson	= json_decode($strData);
		if($isLatLng == 0 ) return $arrJson;
		else {
			$strStatus = $arrJson->status;
			if($strStatus == 'OK') {
				$arrResult = $arrJson->results;
				$arrResult = isset($arrResult[0]) ? $arrResult[0] : null;
				if(isset($arrResult)) {
					return $arrResult->geometry->location;
				}
			} 
			return null;
		}
	}
}
